import { AutoCenter, Button, DotLoading, Modal, Popup, Toast } from "antd-mobile";
import React, { useEffect, useState } from "react";
import requewt from "@/utils/requewt";
import { API, BASE_PATH } from "@/config";
import callFeedback from "@/components/common/modalFeedback";
import { useRouter } from "next/router"
import { KvBrandComp } from "@/components/common";
import { signIn, useSession } from "next-auth/react";
import { useCookies } from "react-cookie";
import { checkENV2, WECHAT, HC, isValidArr, reloadSession, calcCrow, navigateTo,triggerAppShare, checkENV } from "@/utils";
import { motion } from "framer-motion";
import classNames from "classnames";
import Image from "next/image";
import { ResultComp } from "@/components/pages/prize";
import GameResult from "@/components/common/modalFeedback/game.result";

export default function () {
  const [loading, setLoading] = useState(false);
  const {data: userinfo} = useSession();
  const [cookies] = useCookies(['name']);
  const [visible, setVisible] = useState(false);
  const [status, setStatus] = useState(undefined);
  const [user, setUser] = useState(undefined);
  const [data, setData] = useState(undefined);
  const [remain, setRemain] = useState(0);
  const router = useRouter();
  console.log(userinfo,cookies)
  const containerVar = {
    hidden: {opacity: 0},
    visible: {
      opacity: 1,
      transition: {
        delayChildren: 0.05,
        staggerChildren: 0.05,
      }
    },
    exit: {y: 50, opacity: 0},
  };

  const itemVar = {
    hidden: {y: 30, opacity: 0},
    visible: {
      y: 0,
      opacity: 1,
    },
  };

  const carVar = {
    hidden: {x: `-100%`, opacity: 0},
    visible: {
      x: 0,
      opacity: 1,
      transition: {
        delay: .4
      }
    },
    exit: {
      x: `100%`
    }
  };

  const qiVar = {
    hidden: {scale: 0, opacity: 0},
    visible: {
      scale: 1,
      opacity: 1,
      transition: {
        delay: .6,
        duration: 0.3
      }
    },
  };

  const itemVerticalLeftVar = {
    hidden: {x: -50, opacity: 0},
    visible: {x: 0, opacity: 1},
  };

  const itemVerticalRightVar = {
    hidden: {x: 50, opacity: 0},
    visible: {x: 0, opacity: 1},
  };

  const titleVar = {
    hidden: {x: -100, opacity: 0},
    visible: {
      x: 0,
      opacity: 1,
    },
  };

  const floatVar = {
    visible: {
      y: [0, 20, 0, -20, 0],
      rotate: [0, 2, 0, -2, 0],
      transition: {
        ease: `linear`,
        duration: 10,
        repeat: Infinity,
      }
    },
  };

  useEffect(() => {
    (async () => {
      if (!userinfo) return;
      setUser(userinfo?.user);
      // await handler.fetch();
    })()
  }, [userinfo])

  useEffect(() => {
    (async () => {
      handler.getUserInfo()
      // await handler.check();
      // await handler.remain()
    })()

    return () => {
      Toast.clear();
      Modal.clear()
    }
  }, [])

  const handler = {
    check: async () => {
      const resp = await requewt(API.prize.check);
      console.log(`resp`, resp)
      if (resp?.error_code !== 0) {
        await Toast.clear();
        await callFeedback({title: resp?.msg || `请求失败`});
        return;
      }
      if (resp?.data === 1) {
        await handler.reward()
      }

    },
    reward: async () => {
      const resp = await requewt(API.prize.reward);
      console.log(`resp`, resp)
      if (resp?.error_code !== 0) {
        await Toast.clear();
        await callFeedback({title: resp?.msg || `请求失败`});
        return;
      }

      const m = callFeedback({
        bodyClassName: `act-feedback-modal cp-prize-result close-hidden`,
        content: <div className="inner">
          <ResultComp handler={handler} result={resp?.data} />
        </div>,
        actions: <>
          <Button shape={`rounded`} key={1}
                  className="act-btn act-btn-bevel"
                  onClick={e => m.close()}
          >
            确定
          </Button>
          {
            resp?.data?.status === 0 &&
            <Button shape={`rounded`}
                    className="act-btn act-btn-bevel"
                    onClick={e => navigateTo(`/lottery`)}
            >
              去抽奖
            </Button>
          }
        </>,
        closeOnAction: true,
        closeOnMaskClick: true,
      })
    },
    enter: async (item) => {
      // await router.push(`/game`)

      // return
      // if (!remain) {
      //   const m = callFeedback({
      //     bodyClassName: `act-feedback-modal cp-game-result close-hidden close-at-center-bottom`,
      //     content: <div className="inner">
      //       <div className="header">
      //         <img src={`${BASE_PATH}/img/game/game-result-header-fail.png`} alt="" />
      //       </div>
      //       <div className="content">
      //         <img className="img-fluid" src={`${BASE_PATH}/img/game/no-remain.png`} alt="" />
      //       </div>
      //     </div>,
      //     actions: [
      //       <Button shape={`rounded`}
      //               className="act-btn act-btn-bevel"
      //               onClick={e => {
      //                 m.close()
      //               }}
      //       >
      //         确定
      //       </Button>
      //     ]
      //   })
      //
      //   return
      // }
      // console.log(user,'usersss')
      // return
      const resp = await requewt(API.user.userActivity);
      if(resp?.error_code !==0) {
        return callFeedback({
          bodyClassName: 'act-feedback-modal ',
          title: <div  dangerouslySetInnerHTML={{__html: resp?.msg || '请求游戏失败'}}></div>,
          content:<AutoCenter style={{marginTop:'10px'}}>
            <div style={{height:'80px'}}></div>
          </AutoCenter>,
          closeOnAction:false,
          hideClose:true,
          closeOnMaskClick: false,
          actions: [
            <Button
            key="confirm"
            className="act-btn"
            onClick={async () => {
              const env = await checkENV2()
              console.log(env,'env')
              if (env === 'mini') {
                wx?.miniProgram.navigateBack && wx?.miniProgram.navigateBack({})
            } else if (env === 'app') {
                window?.UNIApp?.closePage()
            }
            }}
          >确 定</Button> 
          ]
        })
        
      }

      // if (user?.is_robot) {
      //   setVisible(true);
      //   setTimeout(() => {
      //     HC(handler.humanCheck, item)
      //   }, 300)
      //   return
      // }
      
      Toast.show({content: `进入中`, icon: `loading`});
      
      await router.push(`/game`)
      // const env = await checkENV2();
      Toast.clear()
      
      
      // window.location.href = `/treasure1021/game`
    },
    remain: async () => {
      setLoading(true);
      const resp = await requewt(API.game.remain);
      setTimeout(() => setLoading(false), 300);
      if (resp?.error_code !== 0) {
        await callFeedback({title: resp?.msg || `请求失败`});
        return;
      }
      setRemain(resp?.data);
    },
    humanCheck: async (values, record) => {
      if (!values) return;
      const options = {
        method: `POST`,
        headers: {"Content-Type": `multipart/form-data`},
        body: values
      }
      const resp = await requewt(API.user.check, options);
      if (resp?.error_code !== 0 || resp?.[`msg`] !== `ok`) {
        await callFeedback({title: resp?.msg || `验证失败`});
        setVisible(false);
        return;
      }
      setVisible(false)
      const {auth} = cookies || {};
      await signIn("credentials", {
        token: auth, redirect: false
      });

      reloadSession()
      // handler.enter()
      await router.push(`/game`)
    },
    getUserInfo: async () => {
      const resp = await requewt(API.user.userinfo);
      console.log(resp)
      if (resp?.error_code === 0 && resp?.msg === `ok`) setUser(resp?.data);
    }
  }

  return (
    <>
      {/* <KvBrandComp /> */}

      <div className="deco-wrapper">

        
      <motion.div
          className="inner"
          variants={containerVar}
          initial="hidden"
          animate="visible"
          exit="exit"
        >
          <motion.div style={{position:'absolute',bottom:'23vh',width:'100vw'}}>
          <motion.img src={`${BASE_PATH}/img/game/home-icon-1.png`}
                      alt="deco-cloud-b-l"
                      className=" deco-icon4"
                      style={{width:'100%'}}
                      // variants={floatVar}
  //                     animate={{ x: global.innerWidth*0.06 }}
  // transition={{ ease: "easeOut", duration: 1 }}
          />
          <motion.img
            src={`${BASE_PATH}/img/game/home-icon-2.png`}
            width={326}
            alt="deco-cloud-b-l"
                      className="deco-car deco"
                      variants={carVar}
          />
          </motion.div>
        </motion.div>

       
        
      </div>

      <div className="landing-footer">
        <div className="inner">
          <Button className={`act-btn act-btn-bevel start-btn`} onClick={e => handler.enter()}>
            {/* 开始游戏 */}
          </Button>
          
        </div>
      </div>


      <Popup
        visible={visible}
        onMaskClick={() => {
          setVisible(false)
        }}
        position='bottom'
        destroyOnClose={true}
      >
        <div className="human-check">
          <div className="title">安全验证</div>
          <div id="nc" />
        </div>
      </Popup>

    </>
  )
}